define(function(require, exports) {
	var pubjs = require('pubjs');
	var util = require('util');
	var view = require('@base/view');

	function _getItemType(item) {
		if (!item){
			return null;
		}
		var types = [];
		for (var i in item) {
			switch (i) {
				case 'PositionIds':
					if (item[i].length) {
						return 'Spot';
					}
					break;
				case 'Type':
				case 'Size':
				case 'Domain':
				case 'SiteClass':
				case 'Screen':
					if (item[i].length) {
						types.push(i);
					}
					break;
			}
		}
		return types.length ? types.sort() : null;
	}

	// 活动编辑，特殊条件
	var Base = view.container.extend({
		init: function(config) {
			config = pubjs.conf(config, {
				max_list: 10,
				WhiteBlackType: 1,
				gridConfig: {
					default_sort: false,
					auto_load: false,
					hasSearch: false,
					hasPager: false,
					hasTab: false,
					hasExport: false,
					hasAmount: false,
					opClick: true,
					list: {
						scroll_type: "row",
						scroll_size: 10
					},
					cols: [{
						type: 'id',
						text: LANG('优先级')
					}, {
						name: 'Kind',
						text: LANG('类型'),
						render: 'renderKind',
						width: 40
					}, {
						name: 'Name',
						type: 'index'
					}, {
						name: 'Size',
						text: LANG('广告位数量'),
						render: 'renderCount',
						align: 'center',
						width: 100
					}, {
						name: 'operation',
						type: 'op',
						width: 100,
						render: 'renderOperation'
					}]
				},
				view_model: {
					// 导入按钮点击事件
					evImportBtnClick: this.eventImportBtnClick
					// 导出按钮点击事件
					,evExportBtnClick: this.eventExportBtnClick
					// 清空
					,evClearBtnClick: this.eventClearBtnClick
				}
			});

			// 渠道id
			this.$exchangeId = 0;

			this.Super('init', arguments);
		}
		,afterBuild: function() {
			this.append([
				'<div class="button-wrap pr">',
					'<div class="pa" style="top: -30px;left: 0">',
						'<button ms-click="evClearBtnClick" class="btn btn-danger mr15">' + LANG('删除所有') + '</button>',
						'<button ms-click="evImportBtnClick" class="btn btn-default mr15">' + LANG('导入') + '</button>',
						'<button ms-click="evExportBtnClick" class="btn btn-default">' + LANG('导出') + '</button>',
					'</div>',
				'</div>',
				'<div pub-name="grid" pub-mod="@base/grid.base" class="grid-wrap" />'
			].join(''));

			// 导入导出窗口
			this.createAsync('dialog', 'modules/importExport.base', {'noProcess': true});

			// 查看窗口
			this.createAsync('view', 'campaign/popwin/view.base');

			this.buildFromTemplate({
				grid: this.getConfig('gridConfig')
			});
		}
		// 展现类型
		,renderKind: function(idx, val) {
			var html = '<em class="P-campaignEditAddon-{icon}" title="{title}"></em>';
			return html
				.replace('{icon}', (val == 1 ? 'runing' : 'invaild'))
				.replace('{title}', (val == 1 ? LANG('白名单') : LANG('黑名单')));
		}
		// 渲染显示广告位记录名称
		,renderName: function() {
			return '-';
		}
		// 渲染计算广告位数量
		,renderCount: function(idx, val, row) {
			return row.PositionIds && row.PositionIds.length || '--';
		}
		// 渲染操作列
		,renderOperation: function(idx, val, row) {
			var ops = ['<a href="#" data-op="remove">删除</a>'];
			if (row.PositionIds){
				ops.unshift('<a href="#" data-op="view">查看</a>');
			}
			return ops.join(' | ');
		}
		,reset: function() {
			// 渠道id
			this.$exchangeId = 0;
			this.$data = [];
			this.$.grid.setData([]);
		}
		,getData: function() {
			return this.$data;
		}
		,setData: function(data) {
			this.$data = data || [];
			this.$.grid.setData(this.$data);
			return this;
		}
		,importData: function() {
			this.$.dialog.setTitle(LANG('导入特殊条件')).setData('').show();
		}
		,exportData: function() {
			var formatData = JSON.stringify( this.$data );
			this.$.dialog.setTitle(LANG('导出特殊条件')).setData(formatData).show();
		}
		// 删除广告位分组
		,removeGroup: function(index){
			var self = this;
			var list = self.getData();
			pubjs.confirm(LANG('要删除广告位分组: %1 吗?', list[index].Name || LANG('默认分组')), function(isOk){
				if(isOk){
					list.splice(index, 1);
					self.setData(list);
				}
			});
			return self;
		}
		// 查看广告位分组
		,viewGroup: function(index) {
			var self = this;
			var data = self.getData();
			self.$index = index;
			self.$.view.reset().setParam({
					index: index,
					ChannelId: self.$exchangeId
				}).setValue(data[index]).show();

			return self;
		}
		,eventImportBtnClick: function(ev) {
			this.importData();
		}
		,eventExportBtnClick: function(ev) {
			this.exportData();
		}
		,eventClearBtnClick: function() {
			this.setData();
		}
		// 渠道更改消息, 渠道变更时广播
		,onExchangeIdChange: function(ev) {
			this.$exchangeId = ev.param;
		}
		,onListOpClick: function(ev){
			var self = this;
			var param = ev.param;
			if (ev.source === self.$.grid){
				switch (param.op){
					case 'remove':
						self.removeGroup(param.index);
					break;
					case 'view':
						self.viewGroup(param.index);
					break;
				}
			}
			return false;
		}
		// 导入消息
		,onImportList: function(ev) {
			var self = this;
			var list = [];
			var data,
				spot_black,
				spot_white,
				// single_item,
				complex = {},
				single_key = '';

			var dataMap = {};

			var list_process = function(item) {
				var type = _getItemType(item);
				var isBlack = (item.Kind != 1);
				var items;
				if (type == 'Spot') {
					items = isBlack ? (spot_black || (spot_black = item)) : (spot_white || (spot_white = item));
					items.PositionIds.push.apply(items.PositionIds, item.PositionIds);

				} else if (type) {
					if (type.length === 1) {
						type = type[0];
						var ids = item[type];
						// 暂时同类型的不合并在一起吧。
						type = (isBlack ? 'black' : 'white') + type + ids[0];

						if (!dataMap[type])
						{
							// 存在记录, 合并
							//dataMap[type].push.apply(dataMap[type], ids);
							//util.unique(dataMap[type]);
						//}
						//else
						//{
							// 新记录, 记录类型和加入队列
							dataMap[type] = ids;
							//single_key = items;
							list.push(item);
						}
					} else {
						// 多条件直接合并
						items = '';
						while (type.length) {
							items += type[0] + item[type[0]];
							type.shift();
						}
						if (!complex[items]) {
							single_key = '';
							complex[items] = 1;
							list.push(item);
						}
					}
				}
			};

			try {
				data = JSON.parse(ev.param);
			} catch (e){}

			if (!util.isArray(data)) {return false;}

			util.each(self.$data, list_process);
			util.each(data, list_process);

			// 合并广告位ID记录
			if (spot_black) {
				util.unique(spot_black.PositionIds);
				list.unshift(spot_black);
			}
			if (spot_white) {
				util.unique(spot_white && spot_white.PositionIds);
				list.unshift(spot_white);
			}

			// 更新模块值
			self.setData(list);

			return false;
		}
		,onViewChange: function(ev) {
			var self = this;
			var data = self.getData();
			data[self.$index] = ev.param;
			self.setData(data);
		}
	});

	exports.base = Base;
});